【发布时间】:2017-10-03 21:18:59
【问题描述】:
我想定义一个带有非类型参数的可变参数模板类,并使用一个嵌套模板类,我可以通过可变参数模板参数之一对其进行专门化。
我的问题类似于C++ variadic template with non-type parameters of different types。但我想对嵌套类进行专门化,作为所有者类的参数之一
struct Data
{
std::string field1;
std::string field2;
bool field3 = false;
int field4 = 0;
};
template <typename ... Types>
struct Wrapper
{
template <Types ... Args>
struct Holder
{
};
};
有效:
using W = Wrapper<decltype(&Data::field1), decltype(&Data::field2), decltype(&Data::field3), decltype(&Data::field4)>;
using H = W::Holder<&Data::field1, nullptr, nullptr, nullptr>;
但我需要将其用作
using H = W::Holder<&Data::field3>;
我该如何实现?
类似的代码
#include <iostream>
#include <string>
#include <type_traits>
struct Data
{
std::string field1;
std::string field2;
bool field3 = false;
int field4 = 0;
};
struct Null;
template <typename T, T>
struct Holder
{
};
template <typename H, typename ... T>
struct Select
: Select <T ... >
{
using Base = Select <T ... >;
using Base::Get;
template <H F>
static Holder<H, F> Get();
};
template <>
struct Select<Null>
{
static void Get();
};
int main()
{
using S = Select<std::string Data::*, bool Data::*, int Data::*, Null>;
using H = decltype(S::Get<&Data::field3>());
static_assert(std::is_same<H, Holder<decltype(&Data::field3), &Data::field3>>::value, "Problem ...");
return 0;
};
但我需要在没有 decltype 和函数的情况下执行此操作
正确的解决方案是
using H = W::Holder<&Data::field3>;
【问题讨论】:
-
对于初学者来说这是模棱两可的,
&Data::field1和&Data::field2具有相同的类型,所以没有办法完成你想要的。此外,实际描述您想要解决的问题可能是有益的,可能是比您在此处走的路径更好的方式。 -
是的,我有点误会了。所有类型都是唯一的。使用 W = Wrapper<:string data:: bool int>;问题是通过参数类型之一的值来选择实体专业化
-
@NirFriedman 你在说什么?发布的代码按原样编译。
-
@n.m.我的错,你是对的。不过,我认为“描述实际问题”的观察是成立的。
-
@Dmitry 请修正你的问题,而不是在这里说你犯了错误。