C++中一个给定类型的非类型模板模板的正确语法

huangapple go评论68阅读模式
英文:

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 &lt;optional&gt;

class A
{
public:
  std::optional&lt;int&gt; i;
};

template &lt;typename C, typename T, std::optional&lt;T&gt; C::*optionalPtr&gt;
class OptionalHolder3
{
    void doStuff(C &amp;c);
};

using OH3 = OptionalHolder3&lt;A, int, &amp;A::i&gt;;

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&#39;t compile
template &lt;typename C, template&lt;class T&gt; std::optional&lt;T&gt; C::*optionalPtr&gt;
class OptionalHolder2
{};

// Doesn&#39;t compile
template &lt;template&lt;class C, class T&gt; std::optional&lt;T&gt; C::*optionalPtr&gt;
class OptionalHolder1
{};

using OH2 = OptionalHolder2&lt;A, &amp;A::i&gt;;
using OH2 = OptionalHolder1&lt;&amp;A::i&gt;;

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 中的概念可能可以用来替代该特化,但需要一些特性来提取 TC

英文:

You might use auto (C++17) for that:

template &lt;auto&gt;
class OptionalHolder; // No definition

template&lt;typename C, typename T, std::optional&lt;T&gt; C::*optionalPtr&gt;
class OptionalHolder&lt;optionalPtr&gt;
{
    void doStuff(C &amp;c);
};

concepts from C++20 might be used instead of that specialization, but it would require some traits to extract T and C.

huangapple
  • 本文由 发表于 2023年6月29日 16:44:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定