Quantcast
Channel: User HolyBlackCat - Stack Overflow
Viewing all articles
Browse latest Browse all 1350

Answer by HolyBlackCat for C++ variadic template with values instead of typenames

$
0
0

This syntax isn't viable, because most types can't be template parameters. Among other things, you can't pass string literals (there are workarounds, but they don't work for your case).

The only viable solution is to pass a functor, e.g. a lambda:

template <class T, auto F>class Sample{public:    T val() { return F(); }};Sample<std::string, []{return std::string{};}> a;          // a.val() returns ""Sample<std::string, []{return std::string("foo");}> b;     // b.val() returns "foo"Sample<std::string, []{return std::string(4, 'a');}> c;    // c.val() returns "aaaa"

But this requires C++20. Pre-C++20 you'd have to replace lambdas with functions (or functor classes), so the syntax wouldn't look as good.


Viewing all articles
Browse latest Browse all 1350

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>