Questions tagged [sfinae]

Substitution failure is not an error. This is a C++ programming technique that allows templates to verify properties about their template parameters, thus allowing different specializations to be used if certain kinds of objects are available.

Filter by
Sorted by
Tagged with
0 votes
2 answers
112 views

Conditionally declare make_unique only if not provided by STL, otherwise, declare using std::make_unique

I have the following code: namespace notstd{ // Only Declare this if std::make_unique exists using std::make_unique; // Only Declare this if std::make_unique DOES NOT exist template<...
Vinny's user avatar
  • 174
4 votes
2 answers
70 views

Concept to define type A to be equal to type B, if B exists [duplicate]

I want TagOrInt<T> to be equal to T::Tag if T has a member type Tag, and equal to int otherwise. Like: template <class T> using TagOrint = typename T::Tag; // if this is valid template <...
Sven Sandberg's user avatar
0 votes
0 answers
76 views

Inferring (at compile-time) which members are read inside method

Consider this code: #include <type_traits> #include <tuple> // Random structs that follow this pattern struct X { int x; using Type = int; }; struct Y { float y; using Type =...
bigmazi's user avatar
1 vote
1 answer
52 views

The implementation of add_rvalue_reference

Why does the result become an rvalue reference when deducing from a function returning type directly for a function type, while the implementation in bool_constant yields the correct type? #include &...
Jonny0201's user avatar
  • 463
0 votes
2 answers
113 views

Understanding SFINAE : declarations of member functions outside of partially specialized classes, and templates within variadic classes

What I want to do: Create an 'InstructionSet' object that is held generically (without having to specify types) by a container (of pointers) elsewhere holds a variable number of instruction objects (...
Irreducible Polynomial's user avatar
3 votes
1 answer
93 views

When would I want to use auto&& instead of decltype(auto) or ->decltype(return-expr) for the return type of a function definition?

Take three functions returning prvalue, lvalue, xvalue: int f(); int& f(int); int&& f(int, int); and call them via a function returning decltype(auto) decltype(auto) returnsDecltypeOf(...
Enlico's user avatar
  • 23.9k
2 votes
3 answers
181 views

How to restrict function template arguments to be specializations of a specific class template

I have a structure like: template <typename Arg1, typename Arg2> class TemplateClass { ... }; template <typename TClass> class UsesTemplateClass { public: UsesTemplateClass( TClass&...
user1806566's user avatar
  • 1,132
0 votes
1 answer
80 views

Check type overloads a given operator

There are many related questions on this topic, but I am still puzzled by the following case: #include <iostream> #include <utility> struct A {}; struct B { void operator + (const B& /...
deponovo's user avatar
  • 1,319
11 votes
2 answers
742 views

Are C++ compilers actually compliant with zero-size array SFINAE rule?

About a year or two ago I read about SFINAE rules in C++. They state, in particular, The following type errors are SFINAE errors: ... attempting to create an array of void, array of reference, array ...
ivanovmp's user avatar
  • 113
1 vote
2 answers
79 views

Is there anyway to restrict c++ template class parameters within one-to-one relationship?

For example, there is a template class: template<typename A, typename B> class Example; If a pair of (A, B) is specialized, then other types cannot specialized with A. For example, (B, C) is ...
lhh2001's user avatar
  • 21
2 votes
1 answer
77 views

Function template detection through SFINAE

I want to write a function that dispatches a lambda either to an external library function template (if this function template exists within the library) or to execute the lambda directly. We can do ...
Hymir's user avatar
  • 853
1 vote
1 answer
54 views

How to build a class composed of std array/vector, correspoding to whether the argument is constexpr

I'm complementing a python-like range class (let's call it Range). I'd like to use std::array to store data if the argument is constexpr, and std::vector otherwise. I wonder if I can use the same ...
Moeda Chaos's user avatar
3 votes
2 answers
98 views

Why is static_assert breaking substitution?

Please, consider the following C++14 code: #include <type_traits> template<typename T> class Bar { static_assert(std::is_destructible<T>::value, "T must be destructible&...
Paulo's user avatar
  • 33
1 vote
0 answers
47 views

how to define template member function with unnamed typename?

I have a problem in defining template member function with unnamed typename. code is down below. #include <iostream> #include <type_traits> class A {}; class B : public A {}; class C { ...
RobsBiz's user avatar
1 vote
1 answer
87 views

SFINAE does not disable one of the functions

I have a packaged_task class which wraps a Callable and has invoke() functions, one if Callable does not take any arguments, and a second one when it does. I get errors accessing typename traits::...
Quest's user avatar
  • 2,763
2 votes
1 answer
60 views

Compilation error when creating SFINAE based constructor

During the implementation of a class that has SFINAE based ctor, I get the next error: In template: no type named 'type' in 'std::enable_if<false, void *>'; 'enable_if' cannot be used to disable ...
Yehonatan's user avatar
0 votes
0 answers
46 views

How to check if a c++ class has a given static member variable, wihtout any prior struct definition? [duplicate]

I would like to check if a type T has a static member variable name: T::name. I saw a lot of solutions (ex: https://stackoverflow.com/a/16000226/5317819, https://stackoverflow.com/a/257382/5317819), ...
T.L's user avatar
  • 634
0 votes
1 answer
29 views

Substitution failure causes a compile error

I'm trying to get a better understanding of SFINAE, and have noticed that the following code yields a compile error if the first enable_if that checks whether the non-type parameter g has a function ...
biubiuty's user avatar
  • 492
1 vote
1 answer
28 views

Failed to compile program when trying to define member function conditionally using std::enable_if in C++

I'am writing a simple class with some member functions as usual, and this time I'am trying to define a member function only when the template parameters of the class meet some conditions, but the ...
mk_g_d's user avatar
  • 11
1 vote
1 answer
97 views

Discluding Constructor Signature from Evaluation in C++23

C++ Standard: 20 or 23 test_property.cpp #include <string> #include <tuple> #include "property.h" class object { public: int index() const { return this->_idx; } ...
fauxanadu's user avatar
0 votes
1 answer
34 views

Using std::enable_if with complex predicates

Having to use C++14 I'd like to use std::enable_if to make a function only being available given certain constraints. I do so using or_<> taken from the libc header type_traits instead of std::...
bselu's user avatar
  • 304
1 vote
1 answer
72 views

Why doesn't the compiler choose the other overload when I remove template?

I'm trying to write C++ code to understand whether some class has a default constructor or not (without C++20 concepts). The following code works just fine. #include <iostream> class C { public:...
Erik Nouroyan's user avatar
2 votes
2 answers
89 views

Why do I get overload error while using std::enable_if [duplicate]

I want to define two kinds of member functions run according to one template paramter of class. Here is my code: template <int VAL, typename D = std::chrono::seconds, bool IS_DAILY = false> ...
Yves's user avatar
  • 11.8k
2 votes
1 answer
49 views

SFINAE function that returns proper character encoding depending on template type?

I'm creating a class that's writing code strings, The difference between the string and the wring is only what to put in the basic_string, so I'm going to write it as a template class. The problem is ...
Tee Mo's user avatar
  • 23
1 vote
0 answers
62 views

C++ Visual Studio 2022 template SFINAE compile error after upgrade to latest version [duplicate]

My code fails to compile in Visual Studio 2022 after an upgrade, but not on any other compiler that I tested (MacOS Clang, Linux GCC). I was able to track this down to a very simple example. The ...
Lyve's user avatar
  • 218
1 vote
1 answer
80 views

How do I provide a more compact definition for the specialized template classes?

Consider the following scenario: template < typename T, bool B = std::is_default_constructible_v<T>> class toy_example; template<typename T> class toy_example<T, true> ...
buzzysin's user avatar
  • 311
1 vote
1 answer
51 views

is google::protobuf::RepeatedField<int>::iterator incrementable? compare to const int*/int*

What's the difference in type deduction? The second line fails, but why? decltype(++std::declval<int*&>()) pri = {nullptr}; decltype(++(std::begin(std::declval<google::protobuf::...
Kamil Płani's user avatar
4 votes
1 answer
72 views

Can calls to member functions of function parameters be used as template arguments?

#include <type_traits> template<class T> auto f(T x) -> std::enable_if_t<x.size() == 4>; is valid for Clang and MSVC, but invalid according to GCC. Which is correct? https://...
Roland Schulz's user avatar
1 vote
2 answers
93 views

Detecting if a generic lambda with certain arguments is invocable

I am experimenting with some lambda detection functionality. What I am trying to achieve is to be able to detect if I can call a lambda F with an argument of type const C& returning a result ...
Dmitriy Kumshayev's user avatar
2 votes
3 answers
84 views

Reliable way of ordering mulitple std::void_t partial specializations for type traits

I want to classify the "level of feature support" for a type. The type can contain aliases red and blue. It can contain just one, both , or neither, and I want to classify each of these ...
Jan Schultke's user avatar
  • 22.4k
0 votes
1 answer
61 views

Function Overloading failed

When comparing two methods, if one method has a better match than the other solely based on the method's signature. And that better match ,method fails after deduction, why does the compiler directly ...
Tim H's user avatar
  • 3
2 votes
1 answer
96 views

How do I specialize a templated function for types that have a particular method name?

A third-party library provides us with a function that looks something like this (obviously the actual function is much more complicated): template<typename T> std::string toString(const T& ...
Harry Williams's user avatar
3 votes
2 answers
333 views

How to detect if a enum is defined

Let's say I have the following code: // exposition-only, I can't use this macro in my solution #if defined(HAS_MY_ENUM) enum my_enum { zero, one, }; #endif enum empty { placeholder, // an ...
ivaigult's user avatar
  • 6,258
5 votes
1 answer
148 views

Have difficulty understanding the syntax of generic lambdas for SFINAE-based traits

I am reading some examples of SFINAE-based traits, but unable to make sense out of the one related to generic lambdas in C++17 (isvalid.hpp). I can understand that it roughly contains some major parts ...
Lucien's user avatar
  • 61
0 votes
2 answers
93 views

Templated function with optional compile time arg

I have the following templated functions with an optional port argument, which should be recognized at compile time: template<typename T> void inner(T arg1){...} template<typename T> void ...
Wör Du Schnaffzig's user avatar
4 votes
2 answers
74 views

How to disambiguate the overloads of the `erase_all_if` function template?

I have two implementations of the erase_all_iffunction template. template <typename Container, typename Pred> typename Container::size_type erase_all_if(Container& c, Pred&& pred) { ...
bobeff's user avatar
  • 3,573
0 votes
0 answers
48 views

ambiguos call with SFINAE and default template parameters

I have a code that should implement SFINAE to resolve between two different methods, which however have a different template signature: one has an additional non-type template parameter. As suggested ...
francesco's user avatar
  • 7,304
0 votes
0 answers
42 views

What does it mean to write template <> between "struct struct_name" and "{" when define a struct [duplicate]

Some days ago, I asked a question below: I'm trying to write a hash table demo. By using chain to solve hash collision. I want to write some code like below(pseudo code) that to check if the class put ...
wangjianyu's user avatar
2 votes
1 answer
108 views

How to check if a class has one or more methods with a given name?

There are many different tricks for checking whether a class Foo has a method named bar. For example: If we care about the method signature, we build a trait around something like std::void_t<...
Parker Coates's user avatar
1 vote
0 answers
42 views

Code in if-constexpr branch not taken causing compile errors [duplicate]

Consider the following piece of code with a conditional signature of the function foo based on a constexpr flag. This flag is also checked before calling the function in order to guarantee that the ...
Keltek's user avatar
  • 522
0 votes
2 answers
78 views

How to make a template function in C++ to define a bit representation of any type

template<typename T> std::string bit_representation(T &&type) { uint8_t data[sizeof(T)]; if constexpr (std::is_copy_constructible_v<T>) { T tmp(type); std::...
vanyabeat's user avatar
1 vote
2 answers
164 views

How does C++ template specialization work with default boolean value?

I am looking through libc++'s code and I have noticed this snippet: // __pointer _LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_pointer, pointer); template <class _Tp, class _Alloc, class ...
Bob Fang's user avatar
  • 7,061
0 votes
1 answer
49 views

How can I use enable_if to enable a template function based on what type an iterator iterates over?

I currently have a function that looks like this: template<typename input_iterator> std::string doit(input_iterator beg, input_iterator end) { static_assert(sizeof(*beg) == 1,...
jkb's user avatar
  • 2,406
1 vote
1 answer
187 views

Getting a "Too many template parameters in template redeclaration" error in C++

I'm trying to use std::enable_if to selectively enable functions on a class based on the value of an enum passed to it. Here's how I'm currently trying to do it: // class def template<MyEnum E> ...
SprintKeyz's user avatar
0 votes
1 answer
65 views

member variable detection based on sfinae not work

Given the following code. I want to detect any class that has an age member field based on sfinae. template <typename> struct Void { using type = void; }; template <typename T, typename U =...
Guo Cheng's user avatar
0 votes
1 answer
68 views

SFINAE: Using template child of a template struct

What is the proper way of doing such things? I would like to use conditions on parametrs pack like: static_assert(all_of<ChildTypes ...>::are_in<ParentTypes ...>::value); In short I have ...
Adrian Czupak's user avatar
0 votes
0 answers
29 views

Testing whether template parameter `U` is the same as `C<T>` for any `T` [duplicate]

Consider the following code: template<typename T> class C{ //... } template<typename U> void foo(U arg){ //... } Inside of foo(), how can I test whether U is the same type as C&...
Museful's user avatar
  • 6,771
0 votes
0 answers
51 views

template struct declared twice for checking method existence

I am trying to understand that block of code found in an answer of this question : template template class, call a function if it exists template <typename T, typename = int> struct HasReserve : ...
Arnaud Mégret's user avatar
0 votes
1 answer
73 views

Extract underlying value_type from the container

I'm trying to extract value type from the container. It turns out that most std containers have a value_type, but maps, unfortunately, use it for other purposes. So, I have tried to create a code that ...
dEmigOd's user avatar
  • 538
2 votes
2 answers
234 views

Overload resolution with enable_if

Recently, I was asked this question on an interview: Which Vector constructor will be called in the code below? #include <iostream> class Iterator { public: Iterator(int &x): ptr_(&x)...
Amir Mokhammed-Ali's user avatar

1
2 3 4 5
37