假设有以下课程:
class JsonDocument
{
public:
using RootType = size_t;
constexpr static RootType ObjectRoot = 1;
constexpr static RootType ArrayRoot = 2;
template<
RootType T = ObjectRoot,
std::enable_if<T == ObjectRoot || T == ArrayRoot>
>
JsonDocument();
};
我想专门为
JsonDocument
和 ObjectRoot
构建 ArrayRoot
构造函数。问题是,由于没有参数,所以无法推断出T
。明确地专门化它是行不通的,这样也行不通:
class JsonDocument
{
// ...
// Doesn't work
template<> JsonDocument<ObjectRoot>();
template<> JsonDocument<ArrayRoot>();
}
也不是这个:
template<> JsonDocument::JsonDocument<ObjectRoot>()
{
}
template<> JsonDocument::JsonDocument<ArrayRoot>()
{
}
那么这根本不可能吗?有什么办法可以做到吗?
P.S.:这个问题是不同的;因为可以扣除。
让整个班级成为模板。我认为这是有道理的,因为无论如何您都将在编译时选择要使用的根。 (C++17 示例)
#include <type_traits>
struct ObjectRoot
{};
struct ArrayRoot
{};
// helper constexpr for readability (in C++20 consider a concept)
template<typename root_t>
constexpr bool is_valid_json_root = std::is_same_v<root_t, ObjectRoot> || std::is_same_v<root_t, ArrayRoot>;
template<typename root_t,typename enable_t = void>
class JsonDocument;
template<typename root_t>
class JsonDocument<root_t,std::enable_if_t<is_valid_json_root<root_t>>>
{
public:
// no need for compile time constants.
// you make the selection for your root_t at compile time anyway
//using RootType = size_t;
//constexpr static RootType ObjectRoot = 1;
//constexpr static RootType ArrayRoot = 2;
JsonDocument() {}
};
int main()
{
JsonDocument<ObjectRoot> doc_from_root;
JsonDocument<ArrayRoot> doc_from_array;
}