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.

sfinae
Filter by
Sorted by
Tagged with
4 votes
2 answers
469 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,398
5 votes
1 answer
157 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
111 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,593
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,354
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
121 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
  • 618
0 votes
2 answers
86 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
210 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,191
0 votes
1 answer
51 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,428
1 vote
1 answer
314 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
80 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
72 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
53 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
87 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
  • 558
2 votes
2 answers
244 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 vote
1 answer
56 views

How to deduce types by template integers in C++

I have code: template<int I, typename = void> struct indexed_type { using type = void; indexed_type() { std::cout << "I is void: " << I << std::endl; } }; ...
0xff's user avatar
  • 15
1 vote
1 answer
66 views

How to automatically substitute the type of the returned template с++

Is it possible in c++ to automatically substitute a data type from a template return value, without specifying a specific type in parentheses? I am practicing metaprogramming and tried to execute the ...
Artem Bystrov's user avatar
0 votes
0 answers
2k views

Subsitution failure not in immediate context does not throw a hard error in C++

I am a fresher to C++ template and just learning SFINAE and relating features in C++. Background and the code I am reading a post from here. In that post, author tries to implement boost hana's ...
huangjl's user avatar
  • 85
1 vote
1 answer
57 views

Add sfinae to a constructor allowing only the boost::geometry point types

boost::geometry provides for planar Cartesian coordinates two classes to define a point, using a given floating point type (double, float, ...): (assume namespace bg = boost::geometry; in the ...
kebs's user avatar
  • 6,537
2 votes
1 answer
105 views

template specialization and default template parameters and sfinae

I have put together an example on creating a base template with a number of specializations. #include <iostream> template<typename T, typename U = void> struct foo { static void apply(...
Blair Davidson's user avatar
0 votes
1 answer
66 views

When I try to call SFINAE "createLog" function in C++ I get an Microsoft extension error

I'm trying to call SFINAE createLog function, which is used to append argument to log and message parameters. Compiler always throws use of member 'createLog' before its declaration is a Microsoft ...
xarxarx's user avatar
  • 31
2 votes
1 answer
132 views

Difficulty in verifying valide calls with boost::hana::is_valid

I have a class Foo that can be constructed from C-style strings, string views and non-temporary strings (in reality it contains other members and methods, and it is templated on the character to pass ...
Enlico's user avatar
  • 25.5k
2 votes
2 answers
117 views

Why when use enable_if in class template have to set the second parameter's default type as void?

I'm currently studying enable_if and I have this code: //template<typename T, typename = int/double/float/...> //not working properly template<typename T, typename = void> //works fine ...
Kevin eyeson's user avatar
1 vote
0 answers
75 views

Unconditionally disabling a function with SFINAE

Is the following code valid? If it depends on the C++ version, I would also be interested in the corresponding differences (starting from C++14). #include <type_traits> struct S { template&...
tommsch's user avatar
  • 658
0 votes
1 answer
54 views

Check if a type is the same as a templated type

I have a user defined class template<typename T, int N> class MyClass { // Implementation }; and I want to check on the instantiation of another class if its template parameter is an instance ...
Niteya Shah's user avatar
  • 1,829
1 vote
2 answers
157 views

SFINAE + template specialization

I need an image class template which will work with images with different number of dimensions and different format. And I also want to define different class template specializations for 1D, 2D and ...
postcoital.solitaire's user avatar
2 votes
2 answers
177 views

Detect if map implementation supports incomplete types

I want to see if a map implementation supports incomplete types, as libc++ seems to support them, but not stdlibc++. I tried SFINAE here, but it gives a compilation error: template<template<...
Artefacto's user avatar
  • 97.2k
0 votes
0 answers
19 views

std::enable_if fails to specialize class template while is able to specialize function template [duplicate]

Suppose I have a family of enums with predefined structure: enum class A {BEGIN, a, b, c, END}; Now I need to implement a way to get min and max values (somewhat like numeric limits) which is able to ...
Roman's user avatar
  • 1,416
4 votes
3 answers
92 views

Check with which template parameter a class was instantiated (compile time)

I try to write a metafunction type_par_same_as that selects true_type whenever the template parameter(s) of a class match the given types: Demo #include <type_traits> #include <concepts> #...
glades's user avatar
  • 4,367
2 votes
1 answer
127 views

SFINAE with default argument works with msvc but not with gcc and clang

I've learnt SFINAE in c++. Then I wrote the following program that compiles(and executes) with msvc but not with gcc and clang. Live demo #include <iostream> #include <type_traits> struct ...
Alan's user avatar
  • 1,406
0 votes
2 answers
208 views

Avoid calling of function size_t Print::print(unsigned long long n, int base) if it is not implemented

I maintain an Arduino library which uses the following code (simplified) to print results received by infrared. unsigned long long decodedData; // for 8 and 16 bit cores it is unsigned long ...
Armin J.'s user avatar
  • 455
1 vote
1 answer
186 views

"Class template has already been defined" when making similar but different specializations

I have two class specializations. I want one of them to be used when T::A exists and the other to be used when T::B exists, which should be multually exclusive in practice. I am using std::void_t< ...
John Haggerty's user avatar
1 vote
1 answer
75 views

What normative rules govern and allow SFINAE?

SFINAE, "Substitutation Failure Is Not An Error", is a well-known rule/technique applied during overload resolution of function templates (see e.g. SFINAE @ cppreference). However, it is ...
dfrib's user avatar
  • 72k
1 vote
2 answers
282 views

Deduce types of template-defined base class constructor parameters

I have a derived class, Wrapper, that inherits from a template-defined base class. I'd like to configure Wrapper so that if the base class has constructor parameters, Wrapper's constructor also ...
Conor Taylor's user avatar
  • 3,048
0 votes
1 answer
91 views

How to convert C++17's "if constexpr(std::is_literal_type<T>::value)" to C++11 SFINAE code?

Currently, I have this templated function in my codebase, which works pretty well in C++17: /** This function returns a reference to a read-only, default-constructed * static singleton object of ...
Jeremy Friesner's user avatar
0 votes
1 answer
289 views

"undeclared identifier" with MSVC++ 17.34 (VS 22) within decltype-based SFINAE expression

We are trying to update a C++17 project from VS 19 to VS 22, and all of a sudden, our code does not compile anymore. The problem in question arises in two headers of the foonathan/memory libraries, ...
burnpanck's user avatar
  • 2,087
1 vote
1 answer
53 views

bind with enable_if'd member functions

I'm getting tripped up on calling bind on an enable_if'd member function. I've worked around it using if constexpr, but I'm curious what the solution would be for this issue. The code is the simplest ...
Steve's user avatar
  • 11.8k
1 vote
2 answers
73 views

How can I get the type of underlying data in a SFINAE template definition?

Say I have a library function int foo( const T& ) that can operate with some specific containers as argument: std::vector<A> c1; std::list<B>() c2; auto a1 = foo(c1); // ok auto a2 = ...
kebs's user avatar
  • 6,537
0 votes
1 answer
50 views

How to store and process possibly duplicate distributed class coupling information in C++?

I'm writing a template<class ...Ts> class SortedTypeHolder. During compile time instantiation SortedTypeHolder must collect distributed information about all provided ...Ts from their headers ...
soad's user avatar
  • 61
0 votes
1 answer
186 views

Why do partial and full C++ template specializations, that look almost the same, produce different results?

I haven't written many C++ templates till recently, but I'm trying to take a deep dive into them. Fixing one developer's code I managed to produce some compiler behavior that I can't explain. Here is ...
soad's user avatar
  • 61
1 vote
1 answer
505 views

How to Implement Concepts in C++17

I found this great article on how to implement Concepts in C++14. In one section about how to make a compiles checker he gives the following: template <typename ... Ts> using void_t = void; ...
tderensis's user avatar
1 vote
1 answer
78 views

Is there a precedence to type_traits?

I'm pretty new to SFINAE, and was wondering if there's a precidence to which template the compiler will select if multiple std::enable_if_t<true, std::is_...<T>> end up applying to T. Like ...
Anne Quinn's user avatar
  • 12.8k
0 votes
1 answer
133 views

SFINAE in C++98

I am trying to understand how does SFINAE work in C++98. My aim is to write a simple template function that would only be called when an integer is passed. But the plan is to do it without ...
carce-bo's user avatar
  • 475
0 votes
1 answer
67 views

SFINAE for detecting if size method is implemented doesn't work with vector of vector [duplicate]

I expect this code will work with vector of vector but it seems to detect the existence of size only for the external vector. Anyone can help? #include <iostream> #include <vector> /...
Fzza's user avatar
  • 113
0 votes
1 answer
92 views

How to implement metaprogramming in c++ without std::enable_if

I was reading somewhere that it would be possible to do c++ metaprogramming using function overloads instead of SFINAE. I came up with a toy exercise to test this. I want to detect if a particular ...
bradgonesurfing's user avatar
1 vote
3 answers
74 views

Choose std::queue or std::priority_queue, depending on whether "<" is defined

Inspired by SFINAE to check if std::less will work, I come to this: template <typename F, typename S, typename = void> struct QueueImpl { using type = std::queue<std::pair<F, S>>;...
Ziyuan's user avatar
  • 4,401
0 votes
1 answer
100 views

What is the advantage of Hana's type_c-and-declval dance when querying whether a SFINAE-friendly expression is valid?

On the one hand, the function boost::hana::is_valid is presented as follows Checks whether a SFINAE-friendly expression is valid. Given a SFINAE-friendly function, is_valid returns whether the ...
Enlico's user avatar
  • 25.5k
2 votes
0 answers
53 views

SFINAE-ing on a nullary lambda expression calling a non-templated function on a template argument's instance causes compiler error

While experimenting on this, I've hit what seems to be a bug in GCC. Here's the code triggering it #include <type_traits> constexpr auto f = [](int){}; template<typename T> auto ...
Enlico's user avatar
  • 25.5k

1
2
3 4 5
37