[英]How to specialize with a variadic class template
以下示例代碼說明了我的問題:
#include <array>
#include <vector>
#include <iostream>
#include <type_traits>
namespace Vector
{
namespace Intern
{
template <typename T1, typename ...T2>
struct Traits;
// How can I specialize here so that Memory is being assigned properly??
template <typename T1, int N>
struct Traits<T1, int> {
static constexpr bool Static = 1;
using Memory = std::array<T1, N>;
};
template <typename T1>
struct Traits<T1> {
static constexpr bool Static = 0;
using Memory = std::vector<T1>;
};
}
template <typename T1, typename ...T2>
class Object
{
public :
void printd()
{
std::cout << "Is Static: " << Traits::Static << std::endl;
}
private:
using Traits = Intern::Traits<T1, T2...>;
using Memory = typename Traits::Memory;
Memory m_memory;
};
template <typename T1, typename ...T2>
static auto Create(T2&& ...ln) -> decltype(auto)
{
return new Object<T1, T2...>();
}
}
int main()
{
auto static_vector = Vector::Create<int>(10);
static_vector->printd();
auto active_vector = Vector::Create<int>( );
active_vector->printd();
}
我想知道如何專門化traits struct,以便在上面的例子中將Memory類型正確地指定為std :: array,其中N設置為10。
您不能直接使用整數,但可以將整數包裝到類型中。 這可以使用例如std::integral_constant
來完成:
template <typename T1, typename T2, int N>
struct Traits<T1, std::integral_constant<T2, N>> {
static constexpr bool Static = 1;
using Memory = std::array<T1, N>;
};
template <typename T1>
struct Traits<T1> {
static constexpr bool Static = 0;
using Memory = std::vector<T1>;
};
auto static_vector = Vector::Create<int, std::integral_constant<int, 10>>();
把事情簡單化:
#include <array>
#include <vector>
#include <iostream>
#include <type_traits>
namespace Vector
{
struct VariableSize {};
template<std::size_t N> struct FixedSize {};
template<typename T, std::size_t N>
auto Create(FixedSize<N>)
{
return std::array<T, N>();
}
template<typename T, std::size_t N>
auto Create(VariableSize)
{
return std::vector<T>();
}
}
int main()
{
auto static_vector = Vector::Create<int>(Vector::FixedSize<10>());
auto active_vector = Vector::Create<int>(Vector::VariableSize());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.