c++ - Accessing a class member in an if statement using std::is_same -
i'm trying tackle following problem: if
statement depending on whether argument of template specific object or not - , if is, call object's member function. let's want std::string
the snippet:
#include <iostream> #include <string> template <typename t> void is_string(const t& arg) { if (std::is_same<t, const std::string&>::value) std::cout << arg.length() << std::endl; else std::cout << "the argument not string" << std::endl; } int main() { is_string(0); return 0; }
it doesn't compile, following error:
types.cpp: in instantiation of ‘void is_string(const t&) [with t = int]’: types.cpp:13:13: required here types.cpp:7:13: error: request member ‘length’ in ‘arg’, of non-class type ‘const int’ std::cout << arg.length() << std::endl;
i reckon i'm trying achieve might not possible in c++11, appreciate suggestions on how able such thing
in regular if
statement, both branches must valid code. in case int.length()
makes no sense.
in c++1z use constexpr if
:
if constexpr(std::is_same<t, const std::string&>::value) std::cout << arg.length() << std::endl; else std::cout << "the argument not string" << std::endl;
in c++11 (or older) can employ overloading achieve similar result:
void foo(std::string const& str){ std::cout << str.length() << std::endl; } template<typename t> void foo(t const&){ std::cout << "the argument not string" << std::endl; } template <typename t> void is_string(const t& arg) { foo(arg); }
Comments
Post a Comment