1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <vector> #include <string> #include <iostream> template<typename T> void foo(T x) { std::vector<decltype(x.bar())> v; v.push_back(x.bar()); v.push_back(x.bar()); v.push_back(x.bar()); std::cout << v.size() << std::endl; } class MyClass { public: std::string bar() { std::cout << "MyClass.bar is called" << std::endl; return "abc"; } }; int main() { MyClass obj; foo(obj); } |
I2luY2x1ZGUgPHZlY3Rvcj4KI2luY2x1ZGUgPHN0cmluZz4KI2luY2x1ZGUgPGlvc3RyZWFtPgoKdGVtcGxhdGU8dHlwZW5hbWUgVD4Kdm9pZCBmb28oVCB4KSB7CiAgICBzdGQ6OnZlY3RvcjxkZWNsdHlwZSh4LmJhcigpKT4gdjsKICAgIHYucHVzaF9iYWNrKHguYmFyKCkpOwogICAgdi5wdXNoX2JhY2soeC5iYXIoKSk7CiAgICB2LnB1c2hfYmFjayh4LmJhcigpKTsKICAgIHN0ZDo6Y291dCA8PCB2LnNpemUoKSA8PCBzdGQ6OmVuZGw7Cn0KCmNsYXNzIE15Q2xhc3MgewpwdWJsaWM6CglzdGQ6OnN0cmluZyBiYXIoKSB7CgkJc3RkOjpjb3V0IDw8ICJNeUNsYXNzLmJhciBpcyBjYWxsZWQiIDw8IHN0ZDo6ZW5kbDsKCQlyZXR1cm4gImFiYyI7Cgl9Cn07CgppbnQgbWFpbigpIHsKCU15Q2xhc3Mgb2JqOwoJZm9vKG9iaik7Cn0K
prog.cpp: In function ‘void foo(T)’: prog.cpp:7: error: `.' cannot appear in a constant-expression prog.cpp:7: error: a function call cannot appear in a constant-expression prog.cpp:7: error: a function call cannot appear in a constant-expression prog.cpp:7: error: template argument 1 is invalid prog.cpp:7: error: template argument 2 is invalid prog.cpp:7: error: invalid type in declaration before ‘;’ token prog.cpp:8: error: request for member ‘push_back’ in ‘v’, which is of non-class type ‘int’ prog.cpp:9: error: request for member ‘push_back’ in ‘v’, which is of non-class type ‘int’ prog.cpp:10: error: request for member ‘push_back’ in ‘v’, which is of non-class type ‘int’ prog.cpp:11: error: request for member ‘size’ in ‘v’, which is of non-class type ‘int’
-
result: Compilation error (maybe you wish to see an example for C++ 4.7.2)


