我想要一个类似这样的模板:
template<typename T, class U, U SOME_NON_TYPE_ARG>
func1()
{
if SOME_NON_TYPE_ARG is given
{
// do something special
}
// do something with the SOME_NON_TYPE_ARG value.
}我希望函数体取决于是否给出了SOME_NON_TYPE_ARG。
我尝试将U设为std:: optional,但显然optional不能是非类型模板参数的类型。有什么方法可以在C++17中实现这一点吗?
这是我的作品之一,但这更像是一个hack,有没有更好的方法呢?
#include <type_traits>
#include <iostream>
template<typename T> constexpr std::optional<T> typed_nullopt = std::nullopt;
template <typename T, class U = const std::optional<T> &, U SOME_NON_TYPE_ARG = typed_nullopt<T> >
void test_optional_template(T a)
{
if constexpr (SOME_NON_TYPE_ARG == typed_nullopt<T>)
{
std::cout << a << " we do not have non-type arg" << std::endl;
}
else
{
std::cout << a + SOME_NON_TYPE_ARG << std::endl;
}
}
int main()
{
test_optional_template<int, int, 3>(5);
test_optional_template<int>(10);
}输出将为:
8
10 we do not have non-type arg发布于 2019-08-06 04:13:27
重载函数:
template<typename T, class U>
void func1()
{
// Do something
}
template<typename T, class U, U SOME_NON_TYPE_ARG>
void func1()
{
// Do something else
func1<T, U>();
}发布于 2019-08-06 04:13:49
您可以这样做:
template <typename T, auto... Vs>
void func() {
static_assert(sizeof...(Vs) <= 1);
if constexpr (sizeof...(Vs) == 1) {
constexpr auto V = [](auto X){ return X; }(Vs...);
// do something with V
}
}func<int>()不会做任何特别的事情,func<int, 1>()会把V换成1,func<int, 1, 2>()是病态的。
https://stackoverflow.com/questions/57365421
复制相似问题