Accessing a class member in an if statement using std::is_same

后端 未结 2 1748
清酒与你
清酒与你 2021-01-25 18:33

I\'m trying to tackle the following problem: I would like to do an if statement that does something depending on whether the argument of a template is a specific ob

相关标签:
2条回答
  • 2021-01-25 19:09

    In a regular if statement, both branches must be valid code. In your case int.length() makes no sense.

    In C++17 you could simply use constexpr if:

    if constexpr(std::is_same<T, const std::string&>::value)
        std::cout << arg.length() << std::endl;
    else
        std::cout << "The argument is not a string" << std::endl;
    

    demo

    In C++11 (or older) you can employ overloading to 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 is not a string" << std::endl;
    }
    
    template <typename T>
    void is_string(const T& arg) {
        foo(arg);
    }
    

    demo

    0 讨论(0)
  • 2021-01-25 19:09
    void is_string(const std::string& arg) {
      std::cout << arg.length() << std::endl;
    }
    
    template <typename T>
    void is_string(const T& arg) {
      std::cout << "The argument is not a string" << std::endl;
    }
    

    Or, see if your compiler supports the C++17 if constexpr.

    0 讨论(0)
提交回复
热议问题