相关疑难解决方法(0)

元编程:函数定义失败定义了一个单独的函数

这个答案中,我根据类型的is_arithmetic属性定义了一个模板:

template<typename T> enable_if_t<is_arithmetic<T>::value, string> stringify(T t){
    return to_string(t);
}
template<typename T> enable_if_t<!is_arithmetic<T>::value, string> stringify(T t){
    return static_cast<ostringstream&>(ostringstream() << t).str();
}
Run Code Online (Sandbox Code Playgroud)

dyp建议,不是is_arithmetic类型的属性,是否to_string为类型定义是模板选择标准.这显然是可取的,但我不知道如何说:

如果std::to_string未定义,则使用ostringstream重载.

声明to_string标准很简单:

template<typename T> decltype(to_string(T{})) stringify(T t){
    return to_string(t);
}
Run Code Online (Sandbox Code Playgroud)

这与我无法弄清楚如何构建的标准相反.这显然不起作用,但希望它传达了我正在尝试构建的内容:

template<typename T> enable_if_t<!decltype(to_string(T{})::value, string> (T t){
    return static_cast<ostringstream&>(ostringstream() << t).str();
}
Run Code Online (Sandbox Code Playgroud)

c++ templates result-of sfinae template-meta-programming

26
推荐指数
4
解决办法
2030
查看次数

是否可以仅通过标识符检查成员模板的存在?

我们可以检测员function template,variable template, class/ struct/ union templatealias template不知道量或性质template/ non-template参数?

当我试着考虑这个时,没有什么真正想到的.但是让我们有成员函数模板的结构:

struct foo
{
    // Really random. Let's assume we don't know this declaration, just the name "bar"
    template <class T, std::size_t N, class... Args>
    void bar(T a, T b, T(&c)[N], Args const& ...);
};
Run Code Online (Sandbox Code Playgroud)

如何检查foo::bar模板是否存在?

基于实例化的类型特征在这里不适用,因为(理论上)我们不知道应该使用哪些参数,按什么顺序以及有多少参数.也许一些神奇的查找方法是合适的?或者也许这是不可能的?


在搜索时,我发现了这个问题,但答案中的解决方案需要有关性质的知识template.


这是我第一次尝试检测失败struct template:

struct foo
{ …
Run Code Online (Sandbox Code Playgroud)

c++ templates sfinae type-traits c++14

11
推荐指数
1
解决办法
689
查看次数