英文:
Right syntax for a C++ non-type template template with a given type
问题
I have a class templated over a non-type attribute pointer over a template type, here a std::optional
.
#include <optional>
class A
{
public:
std::optional<int> i;
};
template <typename C, typename T, std::optional<T> C::*optionalPtr>
class OptionalHolder3
{
void doStuff(C &c);
};
using OH3 = OptionalHolder3<A, int, &A::i>;
It works well but I was curious if I could make it easier to use, by reducing the number of required template arguments, but I can't find the right syntax:
// Doesn't compile
template <typename C, template<class T> std::optional<T> C::*optionalPtr>
class OptionalHolder2
{};
// Doesn't compile
template <template<class C, class T> std::optional<T> C::*optionalPtr>
class OptionalHolder1
{};
using OH2 = OptionalHolder2<A, &A::i>;
using OH2 = OptionalHolder1<&A::i>;
Is this possible and how do I do it?
英文:
I have a class templated over a non-type attribute pointer over a template type, here a std::optional
.
#include <optional>
class A
{
public:
std::optional<int> i;
};
template <typename C, typename T, std::optional<T> C::*optionalPtr>
class OptionalHolder3
{
void doStuff(C &c);
};
using OH3 = OptionalHolder3<A, int, &A::i>;
It works well but I was curious if I could make it easier to use, by reducing the number of required template arguments, but I can't find the right syntax:
// Doesn't compile
template <typename C, template<class T> std::optional<T> C::*optionalPtr>
class OptionalHolder2
{};
// Doesn't compile
template <template<class C, class T> std::optional<T> C::*optionalPtr>
class OptionalHolder1
{};
using OH2 = OptionalHolder2<A, &A::i>;
using OH2 = OptionalHolder1<&A::i>;
Is this possible and how do I do it?
答案1
得分: 2
你可以使用 auto
(C++17) 来实现这个:
template <auto>
class OptionalHolder; // 无定义
template<typename C, typename T, std::optional<T> C::*optionalPtr>
class OptionalHolder<optionalPtr>
{
void doStuff(C &c);
};
C++20 中的概念可能可以用来替代该特化,但需要一些特性来提取 T
和 C
。
英文:
You might use auto
(C++17) for that:
template <auto>
class OptionalHolder; // No definition
template<typename C, typename T, std::optional<T> C::*optionalPtr>
class OptionalHolder<optionalPtr>
{
void doStuff(C &c);
};
concepts from C++20 might be used instead of that specialization, but it would require some traits to extract T
and C
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论