C++在模板声明中使用默认值

C++ using default values in template declaration

本文关键字:默认值 声明 C++      更新时间:2023-10-16

我有以下代码。。。

#include <iostream>
using namespace std;
template<typename R, R V = R()> R X() { return V; }
int main()
{
    cout << boolalpha << X<bool>() << endl;    
    cout << boolalpha << X<bool, true>() << endl;
    cout << X<int>() << endl;
    cout << X<int, 5>() << endl;
    cout << X<void>() << endl;   // compiler error
    return 0;
}

它适用于bool和int情况,但不在void情况下编译。有办法解决这个问题吗?

我知道这样的代码是可以接受的。。。

void F()
{
    return void();
}

所以需要以某种方式将该行为从模板中删除。

使用std::enable_if在两个函数模板之间进行选择。实例:

#include <iostream>
#include <type_traits>
using namespace std;
template<typename R, R V = R()>
typename std::enable_if<!is_same<R, void>::value, R>::type X() { return V; }
template<typename R>
typename std::enable_if<is_same<R, void>::value, R>::type X() { return; }
int main()
{
    cout << boolalpha << X<bool>() << endl;    
    cout << boolalpha << X<bool, true>() << endl;
    cout << X<int>() << endl;
    cout << X<int, 5>() << endl;
    X<void>(); // You can't print `void` with standard iostreams...
    return 0;
}

您可以创建一个无效类型(None)并指定具有类型特征的返回类型:

#include <iostream>
struct None {};
// It may not be reasonable o provide the operator:
inline std::ostream& operator << (std::ostream& stream, None) {
    return stream;
}
template<typename R>
struct Traits {
    typedef R return_type;
};
template<>
struct Traits<void> {
    typedef None return_type;
};
template<typename R>
typename Traits<R>::return_type X() { return typename Traits<R>::return_type(); }
template<typename R, typename Traits<R>::return_type V>
typename Traits<R>::return_type X() { return V; }
int main()
{
    std::cout << std::boolalpha << X<bool>() << std::endl;
    std::cout << std::boolalpha << X<bool, true>() << std::endl;
    std::cout << X<int>() << std::endl;
    std::cout << X<int, 5>() << std::endl;
    std::cout << X<void>() << std::endl;
    return 0;
}

此外,函数X被一分为二,以避免默认模板参数的问题。