【发布时间】:2018-03-27 19:59:45
【问题描述】:
我有一个 StrongType<> 类在 PoD 上强制执行强类型:
template <typename T, typename TAG>
class StrongType {
private:
std::string mName;
T mValue;
public:
explicit StrongType(std::string n) : mName(n), mValue() {}
explicit StrongType(std::string n, T v)
: mName(n), mValue(std::move(v)) {
}
const T &value() const { return mValue; }
std::string name() const { return mName; }
};
我有一个类,它保留了一个 StrongTypes 的元组,并且需要返回一个非强类型元组(实际上它应该调用一个具有非强类型参数的函数):
struct aTag {};
struct bTag {};
struct cTag {};
using aType = utils::StrongType<int, aTag>;
using bType = utils::StrongType<std::string, bTag>;
using cType = utils::StrongType<int, cTag>;
int main()
{
aType a("a", 2);
bType b("b", std::string {"b"});
cType c("c", 10);
AdvTuple<aType,bType,cType> t(a,b,c);
//auto nt = t.getTuple();
//std::cout << std::tuple_size<decltype(nt)>() << "\n";
//std::cout << std::get<0>(nt) << "\n";
//nt.call([](aType ra, bType rb, cType rc) {
//});
return 0;
}
这是我做的实现,但它没有编译:
#include <tuple>
template <typename ...T>
class AdvTuple {
private:
std::tuple<T...> aTuple;
public:
explicit AdvTuple(T... ts)
: aTuple(std::make_tuple(ts...)) {
}
template <int i>
decltype(std::get<i>(aTuple).value()) get() const {
return std::get<i>(aTuple).value();
}
template <int N = 0, typename ...TA, std::enable_if<N < sizeof...(TA)> >
auto getImpl(std::tuple<TA...> t) {
return std::tuple_cat(std::make_tuple(std::get<N>(t)), getImpl<N+1>(t));
};
template <typename ...Q>
std::tuple<Q...> getTuple() const {
return getImpl<0>(aTuple);
}
};
这是来自编译器的消息(mac 上的 clang):
In file included from
/Users/happycactus/Documents/Progetti/Experiments/tupletraits/main.cpp:3:
/Users/happycactus/Documents/Progetti/Experiments/tupletraits/tupletypes.h:32:16: error: no matching member function for call to 'getImpl'
return getImpl<0>(aTuple);
^~~~~~~~~~
/Users/happycactus/Documents/Progetti/Experiments/tupletraits/main.cpp:25:17: note: in instantiation of function template specialization 'AdvTuple<utils::StrongType<int, aTag>, utils::StrongType<std::__1::basic_string<char>, bTag>, utils::StrongType<int, cTag> >::getTuple<>' requested here
auto nt = t.getTuple();
^
/Users/happycactus/Documents/Progetti/Experiments/tupletraits/tupletypes.h:26:10: note: candidate template ignored: couldn't infer template argument ''
auto getImpl(std::tuple<TA...> t) {
^
1 error generated.
1) 如何解决?
2) 如何使用 lambda / function<> 和推导 PoD 类型来实现 call() 函数?即使不是StrongTyped 也可以。
我可以使用 C++11 和 14。
【问题讨论】:
-
getTuple<Q...>-- 在呼叫站点应该从哪里获得Q...?我不清楚getTuple应该返回什么,来自包含的强类型的T副本的元组? -
您对
std::enable_if的使用是错误的,永远无法推断出非类型参数。std::enable_if_t<N < sizeof...(TA), int> = 0
标签: c++ c++11 tuples c++14 variadic-templates