【问题标题】:Specialization of a template with enable_if in header file头文件中带有 enable_if 的模板的特化
【发布时间】:2020-09-01 13:44:13
【问题描述】:

所以我想做 2 个函数:一个用于数字(带模板),一个用于字符串。 这是我最好的尝试:

标题:

class myIO
{
public:

    template<class Arithmetic,
        class = enable_if_t< is_arithmetic_v <Arithmetic>>
    >
    static Arithmetic Input();

    template<>
    static string Input<string, void>();
};

cpp:

template<class Arithmetic, class>
static Arithmetic myIO::Input()
{
    Arithmetic x;
    //...
    return x;
}

template<>
static string myIO::Input<string, void>()
{
    string x;
    //...
    return x;
}

此实现有效,但如果我想将它与 string 一起使用,我必须使用 string x = myIO::Input&lt;string, void&gt;();

我希望能够只写&lt;string&gt; 而不是&lt;string, void&gt;

这可能吗?

【问题讨论】:

    标签: c++ templates header specialization enable-if


    【解决方案1】:

    答案如下: .h:

    class myIO
    {
    public:
    
        template<class Arithmetic,
            class = enable_if_t< is_arithmetic_v <Arithmetic>>
        >
        static Arithmetic Input();
    
        template<class String,
            class = enable_if_t< is_same_v<String, string> >
        >
        static string Input();
    };
    

    .cpp:

    template<class Arithmetic, class>
    static Arithmetic myIO::Input()
    {
        Arithmetic x;
        // doing something
        return x;
    }
    
    template<class String, class>
    static string myIO::Input()
    {
        string x;
        // doing something
        return x;
    }
    

    附言我实际上尝试过类似的方法 - enable_if_t&lt; typeid(String) == typeid(string), string &gt; - 但它没有用

    【讨论】:

      【解决方案2】:

      你可以这样做

      #include <iostream>
      #include <string>
      class A {
          public:
          template<typename T, typename U>
          static void func()
          {
              std::cout << "Do stuff\n";
          }
      
          template<typename T>
          static void func()
          {
              A::func<T, void>();
          }
      
      };
      
      int main()
      {
          A::func<string>();
          return 0;
      }
      

      【讨论】:

      • 甚至template&lt;typename T, typename U = void&gt; ...我无法让OP发布的代码进行编译。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      相关资源
      最近更新 更多