Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在头文件中使用enable_if专门化模板_C++_Templates_Header_Specialization_Enable If - Fatal编程技术网

C++ 在头文件中使用enable_if专门化模板

C++ 在头文件中使用enable_if专门化模板,c++,templates,header,specialization,enable-if,C++,Templates,Header,Specialization,Enable If,所以我想做两个函数:一个用于数字(带模板),一个用于字符串。 以下是我的最佳尝试: 标题: 类myIO { 公众: 模板 > 静态算术输入(); 模板 静态字符串输入(); }; cpp: 模板 静态算术myIO::Input() { 算术x; //... 返回x; } 模板 静态字符串myIO::Input() { 字符串x; //... 返回x; } 这个实现可以工作,但是如果我想将它与string一起使用,我必须执行string x=myIO::Input() 我希望能够只写而不是 有

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

标题:

类myIO
{
公众:
模板
>
静态算术输入();
模板
静态字符串输入();
};
cpp:

模板
静态算术myIO::Input()
{
算术x;
//...
返回x;
}
模板
静态字符串myIO::Input()
{
字符串x;
//...
返回x;
}
这个实现可以工作,但是如果我想将它与
string
一起使用,我必须执行
string x=myIO::Input()

我希望能够只写
而不是


有可能吗?

你可以这样做

#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;
}
#包括
#包括
甲级{
公众:
模板
静态void func()
{
std::cout答案如下:
.h:

类myIO
{
公众:
模板
>
静态算术输入();
模板
>
静态字符串输入();
};
.cpp:

模板
静态算术myIO::Input()
{
算术x;
//做某事
返回x;
}
模板
静态字符串myIO::Input()
{
字符串x;
//做某事
返回x;
}
p、 事实上,我也尝试过类似的方法-
如果
,那么就启用它,但它不起作用,甚至
模板
…我无法获得OP发布的代码进行编译。
template<class Arithmetic, class>
static Arithmetic myIO::Input()
{
    Arithmetic x;
    //...
    return x;
}

template<>
static string myIO::Input<string, void>()
{
    string x;
    //...
    return x;
}
#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;
}
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();
};
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;
}