替换失败并非错误

替换失败并非错误 (Substitution failure is not an error, SFINAE)是指C++语言在模板参数匹配失败时不认为这是一个编译错误。戴维·范德沃德英语David Vandevoorde最先引入SFINAE缩写描述相关编程技术。[1]

具体说,当创建一个重载函数的候选集时,某些(或全部)候选函数是用模板实参替换(可能的推导)模板形参的模板实例化结果。如果某个模板的实参替换时失败,编译器将在候选集中删除该模板,而不是当作一个编译错误从而中断编译过程,这需要C++语言标准授予如此处理的许可。[2] 如果一个或多个候选保留下来,那么函数重载的解析就是成功的,函数调用也是良好的。

例子

下属简单例子解释了SFINAE:

struct Test {
  typedef int foo;
};

template <typename T>
void f(typename T::foo) {}  // Definition #1

template <typename T>
void f(T) {}  // Definition #2

int main() {
  f<Test>(10);  // Call #1.
  f<int>(10);   // Call #2. 并无编译错误(即使没有 int::foo)
                // thanks to SFINAE.
}

在限定名字解析时(T::foo)使用非类的数据类型,导致f<int>推导失败因为int并无嵌套数据类型foo, 但程序仍是良好定义的,因为候选函数集中还有一个有效的函数。

虽然SFINAE最初引入时是用于避免在不相关模板声明可见时(如通过包含头文件)产生不良程序。许多程序员后来发现这种行为可用于编译时内省(introspection)。具体说,在模板实例化时允许模板确定模板参数的特定性质。

例如,SFINAE用于确定一个类型是否包含特定typedef:

#include <iostream>

template <typename T>
struct has_typedef_foobar {
  // Types "yes" and "no" are guaranteed to have different sizes,
  // specifically sizeof(yes) == 1 and sizeof(no) == 2.
  typedef char yes[1];
  typedef char no[2];

  template <typename C>
  static yes& test(typename C::foobar*);

  template <typename>
  static no& test(...);

  // If the "sizeof" of the result of calling test<T>(nullptr) is equal to
  // sizeof(yes), the first overload worked and T has a nested type named
  // foobar.
  static const bool value = sizeof(test<T>(nullptr)) == sizeof(yes);
};

struct foo {
  typedef float foobar;
};

int main() {
  std::cout << std::boolalpha;
  std::cout << has_typedef_foobar<int>::value << std::endl;  // Prints false
  std::cout << has_typedef_foobar<foo>::value << std::endl;  // Prints true
}

当类型T有嵌套类型foobartest的第一个定义被实例化并且空指针常量被作为参数传入。(结果类型是yes。)如果不能匹配嵌套类型foobar,唯一可用函数是第二个test定义,且表达式的结果类型为no。省略号(ellipsis)不仅用于接收任何类型,它的转换的优先级是最低的,因而优先匹配第一个定义,这去除了二义性。

C++11的简化

C++11中,上述代码可以简化为:

#include <iostream>
#include <type_traits>

template <typename... Ts>
using void_t = void;

template <typename T, typename = void>
struct has_typedef_foobar : std::false_type {};

template <typename T>
struct has_typedef_foobar<T, void_t<typename T::foobar>> : std::true_type {};

struct foo {
  using foobar = float;
};

int main() {
  std::cout << std::boolalpha;
  std::cout << has_typedef_foobar<int>::value << std::endl;
  std::cout << has_typedef_foobar<foo>::value << std::endl;
}

C++标准的未来版本中Library fundamental v2 (n4562)页面存档备份,存于互联网档案馆)建议把上述代码改写为:

#include <iostream>
#include <type_traits>

template <typename T>
using has_typedef_foobar_t = typename T::foobar;

struct foo {
  using foobar = float;
};

int main() {
  std::cout << std::boolalpha;
  std::cout << std::is_detected<has_typedef_foobar_t, int>::value << std::endl;
  std::cout << std::is_detected<has_typedef_foobar_t, foo>::value << std::endl;
}

Boost的使用者在boost::enable_if[3]中使用SFINAE。

参考文献

  1. ^ Vandevoorde, David; Nicolai M. Josuttis. C++ Templates: The Complete Guide. Addison-Wesley Professional. 2002. ISBN 0-201-73484-2. 
  2. ^ International Organization for Standardization. "ISO/IEC 14882:2003, Programming languages — C++", § 14.8.2.
  3. ^ Boost Enable If. [2020-08-18]. (原始内容存档于2008-09-05). 

Read other articles:

Equations of light transmission and reflection This article is about the Fresnel equations describing reflection and refraction of light at uniform planar interfaces. For the diffraction of light through an aperture, see Fresnel diffraction. For the thin lens and mirror technology, see Fresnel lens. Partial transmission and reflection of a pulse travelling from a low to a high refractive index medium. At near-grazing incidence, media interfaces appear mirror-like especially due to reflection ...

 

College athletics conference West Coast ConferenceFormerlyWest Coast Athletic Conference (1956–1989)California Basketball Association (1952–1956)AssociationNCAAFounded1952CommissionerStu Jackson (since 2023)Sports fielded 16 men's: 7 women's: 9 DivisionDivision ISubdivisionnon-footballNo. of teams9HeadquartersSan Mateo, CaliforniaRegionWestern United StatesOfficial websitewww.wccsports.comLocations The West Coast Conference (WCC) — known as the California Basketball Association from 195...

 

Fictional character LikoPokémon characterOfficial artwork of Liko from Pokémon Horizons: The SeriesFirst appearanceThe Pendant That Starts It All: Part One (2023)Designed byKen Sugimori (Initial designs)Voiced byAlejandra Reynoso (English) Minori Suzuki (Japanese)In-universe informationHomeCabo Poco, Paldea Liko (Japanese: リコ, Hepburn: Riko) is a fictional character who appears in the Pokémon anime series. She is one of the main characters, taking over the role of main character from t...

Part of Les Eyzies in Nouvelle-Aquitaine, FranceLes Eyzies-de-Tayac-SireuilPart of Les Eyzies Location of Les Eyzies-de-Tayac-Sireuil Les Eyzies-de-Tayac-SireuilShow map of FranceLes Eyzies-de-Tayac-SireuilShow map of Nouvelle-AquitaineCoordinates: 44°56′10″N 1°01′05″E / 44.936°N 1.018°E / 44.936; 1.018CountryFranceRegionNouvelle-AquitaineDepartmentDordogneArrondissementSarlat-la-CanédaCantonVallée de l'HommeCommuneLes Eyzies Area137.44 km2 (14.46...

 

Italian printer and humanist (1449/1452–1515) Aldus ManutiusManutius, illustration in Vita di Aldo Pio Manuzio (1759)BornAldo Manuzioc. 1449/1452Bassiano (near Rome), Papal StatesDied6 February 1515Venice, Republic of VeniceOther namesAldus Manutius the ElderOccupation(s)Renaissance humanist, printer, publisherKnown forFounding the Aldine Press at VeniceFounding the New Academy Aldus Pius Manutius (/məˈnjuːʃiəs/; Italian: Aldo Pio Manuzio; c. 1449/1452 –...

 

Radio station in Fremont, NebraskaKHUBFremont, NebraskaBroadcast areaFremont, NebraskaFrequency1340 kHzBrandingThe Big DogProgrammingFormatCountryAffiliationsABC Radio, Salem Communications, Westwood OneOwnershipOwnerSteven W. Seline(Walnut Radio, LLC)Sister stationsKFMTHistoryFirst air dateDecember 22, 1939[1]Former call signsKORN (1939–1949)KFGT (1949–1958)Technical informationFacility ID34550ClassCPower500 watts (day)250 watts (night)Transmitter coordinates41°25′58.00″N 96...

Big Trouble in Little China (Original Motion Picture Soundtrack)Soundtrack album by John Carpenter & Alan HowarthReleased1986StudioElectric Melody Studios, Glendale, CaliforniaGenre Electronic rock film score Length45:38 (1986 release)71:35 (1999 release)LabelEnigma Records (1986 release)Super Tracks Music Group (1999 release)ProducerJohn CarpenterJohn Carpenter & Alan Howarth chronology Halloween III: Season of the Witch(1982) Big Trouble in Little China (Original Motion Picture ...

 

Questa voce o sezione sull'argomento edizioni di competizioni calcistiche non cita le fonti necessarie o quelle presenti sono insufficienti. Puoi migliorare questa voce aggiungendo citazioni da fonti attendibili secondo le linee guida sull'uso delle fonti. Segui i suggerimenti del progetto di riferimento. I liga 1967-1968 Competizione I liga Sport Calcio Edizione 42ª Organizzatore PZPN Luogo  Polonia Partecipanti 14 Formula 1 girone all'italiana Cronologia della competizione 1966-...

 

Hinterland territories of the Republic of Venice Terraferma redirects here. For the 2011 drama, see Terraferma (film). Mainland domainsDomini de Teraferma (Venetian)Domain of the Republic of VeniceTurquoise color shows the extent of the Terraferma in 1509.Historical eraEarly modern period• War of Padua 1404–1405• Ludovico Trevisan surrenders the Patria del Friuli  1445• Battle of Maclodio 11 October 1427• Treaty of Lodi 9 April 1454• Treaty of Ba...

American Founding Father and merchant For the Arabist, see Henry Laurens (scholar). For similar names, see Henry Laurence. Henry LaurensLaurens depicted by Lemuel Francis Abbott, 1781 or 17845th President of the Continental CongressIn officeNovember 1, 1777 – December 9, 1778Preceded byJohn HancockSucceeded byJohn JayVice President of South CarolinaIn officeMarch 26, 1776 – June 27, 1777PresidentJohn RutledgePreceded byOffice EstablishedSucceeded byJames ParsonsPresident...

 

City in Marion County, Kansas City in Kansas, United StatesBurns, KansasCityBurns United Methodist Church (2010)Location within Marion County and KansasKDOT map of Marion County (legend)Coordinates: 38°05′23″N 96°53′16″W / 38.08972°N 96.88778°W / 38.08972; -96.88778[1]CountryUnited StatesStateKansasCountyMarionTownshipMiltonPlatted1880Incorporated1905[2]Named forTrain stationGovernment[3][2] • TypeMayor–Council...

 

Orbit with a fixed distance from the barycenter For other uses of orbit, see Orbit (disambiguation). This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: Circular orbit – news · newspapers · books · scholar · JSTOR (April 2020) Isaac Newton's Cannonball. Path C depicts a circular orbit. Part of a series...

Molecular biology method Workflow overview of a ChIP-on-chip experiment. ChIP-on-chip (also known as ChIP-chip) is a technology that combines chromatin immunoprecipitation ('ChIP') with DNA microarray (chip). Like regular ChIP, ChIP-on-chip is used to investigate interactions between proteins and DNA in vivo. Specifically, it allows the identification of the cistrome, the sum of binding sites, for DNA-binding proteins on a genome-wide basis.[1] Whole-genome analysis can be performed t...

 

Financial document exchangeable for money This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Demand draft – news · newspapers · books · scholar · JSTOR (August 2023) (Learn how and when to remove this message) A specimen demand draft. A demand draft (DD) is a negotiable instrument similar to a bill of exchange....

 

Cet article est une ébauche concernant un coureur cycliste allemand. Vous pouvez partager vos connaissances en l’améliorant (comment ?). Pour plus d’informations, voyez le projet cyclisme. Sven TeutenbergSven Teutenberg lors du Tour d'Allemagne 2006InformationsNaissance 18 août 1972 (51 ans)DüsseldorfNationalité allemandeÉquipes professionnelles 09.1993-12.1993Telekom (stagiaire)08.1994-12.1994[n 1]WordPerfect1995Novell1996US Postal Service-Montgomery Bell1997-1998US Post...

Indonesian politician Jefri Riwu Kore4th Mayor of KupangIncumbentAssumed office 22 August 2017PresidentJoko WidodoGovernorFrans Lebu RayaRobert Simbolon (Pj.)Viktor LaiskodatMember of People's Representative CouncilIn office2009–2016PresidentSusilo Bambang YudhoyonoJoko Widodo Personal detailsBornJefirstson R. Riwu Kore (1960-01-13) January 13, 1960 (age 64)Kupang, East Nusa Tenggara, IndonesiaNationality IndonesiaPolitical party Democratic PartyAlma materIndonesia University ...

 

Voce principale: Football Club Internazionale Milano. FC Internazionale MilanoStagione 1999-2000La rosa completa della stagione 1999-2000 Sport calcio Squadra Inter Allenatore Marcello Lippi All. in seconda Narciso Pezzotti Presidente Massimo Moratti Serie A4º (in Champions League)[1] Coppa ItaliaFinalista Maggiori presenzeCampionato: Blanc, J. Zanetti (34)[2]Totale: J. Zanetti (43) Miglior marcatoreCampionato: Vieri (13)[2]Totale: Vieri (18) StadioGiuseppe Meaz...

 

State highway in central Illinois, US Illinois Route 8IL 8 highlighted in redRoute informationMaintained by IDOTLength45.51 mi[1] (73.24 km)ExistedNovember 5, 1918[citation needed]–presentMajor junctionsWest end IL 97 in MaquonMajor intersections US 24 / IL 29 in East Peoria I-74 in East Peoria US 150 in East Peoria East end US 24 / US 24 Bus. in Washington LocationCountryUnited StatesStateIllinoisCounties...

Class of consonantal sounds A voiceless alveolar affricate is a type of affricate consonant pronounced with the tip or blade of the tongue against the alveolar ridge (gum line) just behind the teeth. This refers to a class of sounds, not a single sound. There are several types with significant perceptual differences: The voiceless alveolar sibilant affricate [t͡s] is the most common type, similar to the ts in English cats. The voiceless alveolar non-sibilant affricate [t͡θ̠] or [t͡θ͇],...

 

Flagge des Königreichs Preußen mit dem Monogramm F R {\displaystyle FR} für Friedericus Rex Der Staat Preußen war seit der Königskrönung Friedrichs III. von Brandenburg 1701 bis zur Abdankung von König Wilhelm II. während der Novemberrevolution 1918 ein Königreich. Die Hauptstadt war Berlin. Da es sich um die bedeutendste Zeit in der Geschichte Preußens handelt, wird der Hinweis auf seine Staatsform Monarchie meistens weggelassen und nur von Preußen gesprochen. Vor 1701 existierte ...